package com.kingcore.director.resourcemaster.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Observable;
import java.util.ResourceBundle;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.apache.log4j.Logger;

import wzw.sql.DatabaseOperator;
import wzw.swing.table.IconTableCellRenderer;
import wzw.swing.table.PlainTable;
import wzw.swing.table.PlainTableModel;
import wzw.swing.table.ZebraCrossTableCellRenderer;
import wzw.util.DebugUtils;
import wzw.util.I18nUtil;
import wzw.util.I18nUtils;
import wzw.util.StringUtils;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.base.ui.DirectorPanel;
import com.kingcore.director.core.ui.CommonSearchPanel;
import com.kingcore.director.core.ui.CommonSearchable;
import com.kingcore.director.core.util.DirectorComponentUtils;
import com.kingcore.director.core.util.DirectorFileUtils;
import com.kingcore.director.main.Main;
import com.kingcore.director.main.MainFrame;
import com.kingcore.director.resourcemaster.dao.ResourceMasterDao;
import com.kingcore.director.resourcemaster.dao.impl.ResourceMasterDaoImpl;
import com.sunking.swing.JFileTree;

public class FileExplorerMainPanel extends DirectorPanel
	implements DatabaseOperator,
				ItemListener,
				CommonSearchable,
				ActionListener, MouseListener, KeyListener {
 

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//log object
	private final static Logger log = Logger.getLogger(FileExplorerMainPanel.class);


	//------------------------------ MainTable Begin -----------------
	private PlainTable mainTable = null;

	private static final int MainTable_Column_Index_Name = 0;
	private static final int MainTable_Column_Index_Size = 1;
	private static final int MainTable_Column_Index_Type = 2;
	private static final int MainTable_Column_Index_LastModified = 3;
	private static final int MainTable_Column_Index_Uri = 4;
	public static final int[] MainTable_Columns_Width = {350, 180, 120, Main.MainFrame_Size_Width-350-180-120,0};
	public static final String[] MainTable_Headers = {"Name", "Size", "Type", "LastModified", "uri"};
	private static final int MainTable_Column_Count = MainTable_Headers.length;
	
	private static String tableOldValue = null;
	
	private JSplitPane mainSplitPane = null;
	private static final int MainSplitPane_Left_Width= Main.MainFrame_Size_Width/4;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

//	/**
//	 * This is the default constructor
//	 */
//	public FileExplorerPanel() {
//		this(null);
//	}

	private MainFrame mainFrame = null;
	public FileExplorerMainPanel(MainFrame mainFrame) {
		super(mainFrame); 
		this.mainFrame = mainFrame;
		initializeInterface();
		
		this.update(null, null); //需要自己初始一次了。
//		try {
//			fetchData();
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
		
		constructAfter();
	}
	
	
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initializeInterface() {
		// BorderLayout ...
		this.setLayout( new BorderLayout() );

		this.add( getMainNorthPanel(), BorderLayout.NORTH);
		this.add( getMainSplitPane(), BorderLayout.CENTER);
		this.add( getStatusBar(true), BorderLayout.SOUTH);
		
        this.addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) { 
//            	log.info( this.getClass()+"------------- resize..."+ getWidth()+"X"+getHeight());
//            	int panelWidth = getWidth();
//            	int panelHeight = getHeight();            	
//            	scrollPane.setBounds(new java.awt.Rectangle(1,130, panelWidth-0,
//            			panelHeight -128 ));
//    			scrollPane.setViewportView(getTable());
//            	repaint();
            }
            
			public void componentShown(ComponentEvent e) {
				log.debug("panel:shown"); 	
				//refreshView();  // 不建议这调用，事件不可靠，在上层tabpage切换时候主动调用。
			}
        });
	}

	@Override
	public void refreshView() {
		super.refreshView();
		
		this.getLeftFileTree().requestFocusInWindow();
		setStatus(StatusBar_Index_One, currentStatusInfor);
		System.out.println( DebugUtils.getCallTrace(180) );
	}
 
	private JLabel lbl_location = new JLabel(" Location: ");
	private JPanel mainNorthPanel = null;
	private JPanel getMainNorthPanel(){
		if (mainNorthPanel==null) {
			mainNorthPanel = new JPanel();
			mainNorthPanel.setLayout( new BorderLayout());
			mainNorthPanel.add(lbl_location, BorderLayout.WEST);
			mainNorthPanel.add( getLocationTextField(), BorderLayout.CENTER);

		}		
		return mainNorthPanel;
	}
	
	private JTextField locationTextField = null;

	private JTextField getLocationTextField(){
		if (locationTextField==null) {
			locationTextField = new JTextField();
			locationTextField.addKeyListener(this);
			//locationTextField.setToolTipText("可以在这里直接输入文件位置");
		}
		return locationTextField;
	}
	
	public void setCurrentFolder(String fStr, Object eventSource) {

    	File f = new File(fStr);
    	if (f.exists()) {
	    	try {
	    		if (eventSource!=getLocationTextField()) {
		    		getLocationTextField().setText(fStr);
				}
	    		if (eventSource!=getLeftFileTree()) {  //not if else here.
					getLeftFileTree().setSelectFile(f);
				}
				setTableDatas(fStr);
				
			} catch (Exception e1) {
				log.error(e1);
			}
		}
	}

	private void setTableDatas(String uri) {

//		// set text field
//		getLocationTextField().setText( uri );
		
		// table list
		File file = new File(uri);

		File[] fls = file.listFiles();
		if (fls==null) {
			return ;
		}
		PlainTableModel sortableTableModel = mainTable.getModel();
		
		sortableTableModel.removeAllRows();
//		int rowCount = tableModel.getRowCount();
//		for (int i = 0; i < rowCount; i++) {
//			tableModel.removeRow(0);
//		} 
		
		Object[][] data = new Object[fls.length][MainTable_Column_Count];
		int rowIndex=-1;
		int folderNum = 0;
		for (int i = 0; i < fls.length; i++) {
			file = fls[i];
			String fName = file.getName();
			data[++rowIndex][MainTable_Column_Index_Name] = fName;
			
			if (file.isFile()) {
				long size = file.length();
				size = size/1000 + 1;
				String sizeStr = size +"KB";
				data[rowIndex][MainTable_Column_Index_Size] = sizeStr;
				
				if(fName.lastIndexOf(".")>0){
					data[rowIndex][MainTable_Column_Index_Type] = fName.substring(fName.lastIndexOf("."));
				}else{
					data[rowIndex][MainTable_Column_Index_Type] = "";
				}
				
			}else{
				folderNum++;
				data[rowIndex][MainTable_Column_Index_Size] = "";
				data[rowIndex][MainTable_Column_Index_Type] = "Folder";
			}
			//System.out.println(rs.getString("Location"));
			Timestamp tsp = new Timestamp( file.lastModified() );
			String lastModifiedStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tsp);
			data[rowIndex][MainTable_Column_Index_LastModified] = lastModifiedStr; 
			data[rowIndex][MainTable_Column_Index_Uri] = file.getPath(); 
		}

		// sort data
		Object[][] dataNew = new Object[fls.length][MainTable_Column_Count];
		int folderIndex = 0;
		int fileIndex = folderNum;
		for (int i = 0; i < data.length; i++) {
			if (data[i][MainTable_Column_Index_Type] == "Folder") {
				dataNew[folderIndex++] = data[i];
			}else{
				dataNew[fileIndex++] = data[i];
			}
		}
		
//		for (int i = 0; i < dataNew.length; i++) {
//			sortableTableModel.addRow(dataNew[i]);
//		}
		sortableTableModel.setData(dataNew);
		sortableTableModel.fireTableDataChanged(); //repaint.
//		getMainTable().validate();
//		getMainTable().revalidate();
//		getMainTable().repaint(); 
		
//		DefaultTableModel dtm = (DefaultTableModel) ((SortableTableModel)this.getMainTable().getModel()).getTableModel();
//		dtm.setDataVector(dataNew, LocalSearch_MainTable_Headers);

		currentStatusInfor = StringUtils.replace(statusBar_currentFileListInfo,"${count}", dataNew.length+"");
		setStatus( StatusBar_Index_One, currentStatusInfor);
	}

	private JSplitPane getMainSplitPane(){
		if (mainSplitPane==null) {
			mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false);
			mainSplitPane.add(getLeftScrollPane(),0);
			mainSplitPane.add(getRightSplitPane(),1);
			mainSplitPane.setOneTouchExpandable(true);
			mainSplitPane.setDividerSize(6);
			mainSplitPane.setDividerLocation( MainSplitPane_Left_Width );  //200);
		}
		return mainSplitPane;
	}
	private JScrollPane leftScrollPanel = null;
	private JScrollPane rightScrollPanel = null;
	/**
	 * This method initializes leftScrollPane
	 *
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getLeftScrollPane() {
		if (leftScrollPanel == null) {
			leftScrollPanel = new JScrollPane();
			//leftScrollPanel.setBounds(new java.awt.Rectangle(2, this.clientTop,150, this.clientHeight));
			leftScrollPanel.setViewportView( getLeftFileTree() );	//getJt_tree()
		}
		return leftScrollPanel;
	}

	private JFileTree leftFileTree = null;
	private JFileTree getLeftFileTree(){
		if (leftFileTree == null) {
			leftFileTree = new JFileTree( );  //null for folders,new AllFileFilter() for all file
			
			leftFileTree.addMouseListener( this );
			leftFileTree.addKeyListener( this );
		}
		return leftFileTree;
		
	}

	
	JSplitPane rightPanel = null;
	private JSplitPane getRightSplitPane() {
		if(rightPanel==null){
			rightPanel = new JSplitPane();

			rightPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false);
			rightPanel.setBorder(null);	
			rightPanel.add(getCommonSearchPanel(), JSplitPane.TOP );	
			rightPanel.add(getRightScrollPane(), JSplitPane.BOTTOM );
			rightPanel.setOneTouchExpandable(true);
			rightPanel.setDividerSize(0);
			rightPanel.setDividerLocation( CommonSearchPanel_Hight ); //Main.MainFrame_Size_Height-180
			
		}
		return rightPanel;
	}
	
	private CommonSearchPanel searchPanel = null;
	private CommonSearchPanel getCommonSearchPanel() {

		if(searchPanel==null){
			searchPanel = new CommonSearchPanel(this, this.getMainTable() );
			this.mainFrame.getLanguageManager().addObserver(searchPanel);
		}
		return searchPanel;
	}
	/**
	 * This method initializes jPanel
	 *
	 * @return javax.swing.JPanel
	 */
	private JScrollPane getRightScrollPane() {
		if (rightScrollPanel == null) {
			rightScrollPanel = new JScrollPane();
			//rightScrollPanel.setBounds(new java.awt.Rectangle(158,this.clientTop,432, this.clientHeight));
			
			//rightScrollPanel.setLayout(new BorderLayout());
			//rightScrollPanel.setLayout( new BorderLayout() );
			rightScrollPanel.setViewportView( getMainTable() ); //getTable()
			//rightScrollPanel.setBackground(Color.gray);
		}
		return rightScrollPanel;
	}

	public boolean fetchData() throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean saveData() throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
	}

	private String msgDialog_infoSuccessFailRowNum = null;
	private String msgDialog_infoSuccessRowNum = null;
	public void actionPerformed(ActionEvent e) {

		Object obj=e.getSource();
		// toolBar
		if( obj == jpmi_MainTable_Open){
			executeOpenCurrentFile();
			
		}else if( obj == jpmi_MainTable_OpenPath){
			executeOpenCurrentFileParent(); 
			
		}else if( obj == jpmi_MainTable_AddFileOpenTaskAwoke){
			String fileName = getMainTable().getModel().getValueAt(getMainTable().getSelectedRow(), MainTable_Column_Index_Name).toString();
			String fileUri = getMainTable().getModel().getValueAt(getMainTable().getSelectedRow(), MainTable_Column_Index_Uri).toString();
			this.mainFrame.getReminderMainPanel().executeAddNewFileOpenAwoke(fileUri,fileName);
  		   
		}else if( obj == jpmi_MainTable_Rename){ 
			if (getMainTable().getSelectedRow()<0) {
				return;
			}
			mainTable.editCellAt(getMainTable().getSelectedRow(), MainTable_Column_Index_Name);
			
		}else if( obj == jpmi_MainTable_Delete){
			
			//step: check input 
			int[] selRows = getMainTable().getSelectedRows(); // support multi rows
			if (selRows==null || selRows.length<1) {
				return;
			}
			
			//step: confirm
			if(JOptionPane.showConfirmDialog(this,"确认删除选中的"+selRows.length+"个文件吗？？？"
													,"删除提示",JOptionPane.OK_CANCEL_OPTION)
	 				!=JOptionPane.OK_OPTION)
				return;

			//step: do business
			DefaultTableModel dtm = (this.getMainTable().getModel()).getTableModel();
			for (int selRow : selRows) {
				try {
					String fileUri = getMainTable().getModel().getValueAt(selRow, MainTable_Column_Index_Uri).toString();
					File f = new File(fileUri);
					f.delete();
					
					dtm.removeRow( selRow );				
				} catch (Exception e1) {
					e1.printStackTrace();
				}				
			}
			setStatus( StatusBar_Index_One, "删除文件成功！一共删除了["+selRows.length+"]个文件。" );
					
		}else if( obj==jpmi_MainTable_Add2FileCopy){ 

			//step: check input
			int[] selRows = getMainTable().getSelectedRows(); // support multi rows
			if (selRows==null || selRows.length<1) {
				return;
			}
			
			//step: do business
			String fileName = null;
			String fileUri = null;
			int successNum = 0;
			int failNum = 0;
			for (int i = 0; i < selRows.length; i++) {
				fileName = getMainTable().getModel().getValueAt(selRows[i], MainTable_Column_Index_Name).toString();
				fileUri = getMainTable().getModel().getValueAt(selRows[i], MainTable_Column_Index_Uri).toString();
				try {  //不采用批量处理，成功率低，如果一条有主键冲突则全部失败不好。
					this.mainFrame.getResourceMasterMainPanel()
							.getFileCopyPanel().addFile2CurrentFileCopy(fileUri);
					successNum++;
				} catch (Exception e1) {
					failNum++;
					e1.printStackTrace();
				}				
			}
			
			//step: give notice
			String info = null;
			if (failNum==0) {
				info = StringUtils.replace(msgDialog_infoSuccessRowNum,"${successNum}",successNum+"");
			} else {
				info = StringUtils.replace(msgDialog_infoSuccessFailRowNum,"${successNum}",successNum+"");
				info = StringUtils.replace(info,"${failNum}",failNum+"");
				
			}
			JOptionPane.showMessageDialog(this, info
												, this.msgDialog_info, JOptionPane.INFORMATION_MESSAGE);
			setStatus( StatusBar_Index_One, info.toString() );
			
		}else if( obj == jpmi_MainTable_Add2FavoriteFile){ 

			//step: check input
			int[] selRows = getMainTable().getSelectedRows(); // support multi rows
			if (selRows==null || selRows.length<1) {
				return;
			}
			
			//step: do business
			String fileName = null;
			String fileUri = null;
			int successNum = 0;
			int failNum = 0;
			for (int i = 0; i < selRows.length; i++) {
				fileName = getMainTable().getModel().getValueAt(selRows[i], MainTable_Column_Index_Name).toString();
				fileUri = getMainTable().getModel().getValueAt(selRows[i], MainTable_Column_Index_Uri).toString();
				try {  //不采用批量处理，成功率低，如果一条有主键冲突则全部失败不好。
					this.mainFrame.getResourceMasterMainPanel()
							.getFavoriteFilesPanel().addNewFileToFavorite(fileUri, null);
					successNum++;
				} catch (Exception e1) {
					failNum++;
					e1.printStackTrace();
				}				
			}
			
			//step: give notice
			//StringBuffer info = new StringBuffer("Add to favorite finished. "+successNum+" rows succeed");
			String info = null;
			if (failNum==0) {
				info = StringUtils.replace(msgDialog_infoSuccessRowNum,"${successNum}",successNum+"");
			} else {
				info = StringUtils.replace(msgDialog_infoSuccessFailRowNum,"${successNum}",successNum+"");
				info = StringUtils.replace(info,"${failNum}",failNum+"");
				
			}
			JOptionPane.showMessageDialog(this, info
												, this.msgDialog_info,JOptionPane.INFORMATION_MESSAGE);
			setStatus( StatusBar_Index_One, info.toString() );
			
		}else if( obj == jpmi_MainTable_SearchDisk){
			this.mainFrame.executeLocalSearch();
			//e.consume();
			
		}else if( obj == jpmi_MainTable_Search){
			this.getRightSplitPane().setDividerLocation(CommonSearchable.CommonSearchPanel_Hight);
			this.getCommonSearchPanel().getKeywordTextField().requestFocusInWindow();
			//e.consume();
		}

	}

	public void mouseClicked(MouseEvent e) {
		Object obj = e.getSource() ;
		if (obj == getLeftFileTree()) {
			if(!e.isPopupTrigger() && (e.getClickCount()==2||e.getClickCount()==1) ) {
				 
				// step: get value
				if (getLeftFileTree().getSelectFile()==null) {
					return;   //NullPointException
				}
				String uri = getLeftFileTree().getSelectFile().getPath() ;
				
				setCurrentFolder(uri, getLeftFileTree());
			}
			
		}else if(obj==getMainTable()){
	        //记录进入编辑状态前单元格得数据
			if(mainTable.getSelectedRow()<=mainTable.getRowCount()
					&& mainTable.getSelectedRow()>-1 ){
				tableOldValue = mainTable.getValueAt(mainTable.getSelectedRow(), MainTable_Column_Index_Name)+"";
			}
			// 双击
			if(!e.isPopupTrigger() && e.getClickCount()==2) {
				executeOpenCurrentFile();
			}
		}	
	
	}
	

	private void executeOpenCurrentFile() {
		if (getMainTable().getSelectedRow()<0) {
			return;
		}
		String fileName = getMainTable().getModel().getValueAt(getMainTable().getSelectedRow(), MainTable_Column_Index_Name).toString();
		String fileUri = getMainTable().getModel().getValueAt(getMainTable().getSelectedRow(), MainTable_Column_Index_Uri).toString();
		File f = new File(fileUri);
		//String filePath = f.getParent(); 
		if (f.isFile()) {
			DirectorFileUtils.openFileQuietly(fileUri); 
		} else {  //folder
			setCurrentFolder(fileUri, null);
		}
		
	}
	private void executeOpenCurrentFileParent() {
		if (getMainTable().getSelectedRow()<0) {
			return;
		}
//		String fileName = getMainTable().getModel().getValueAt(getMainTable().getSelectedRow(), MainTable_Column_Index_Name).toString();
		String fileUri = getMainTable().getModel().getValueAt(getMainTable().getSelectedRow(), MainTable_Column_Index_Uri).toString();
//		String filePath = new File(fileUri).getParent(); 
		
		DirectorFileUtils.openFileLocationQuietly( fileUri );  //filePath); 
		
	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseReleased(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj==getMainTable()){
			// 在Table上右击鼠标
			//System.out.println ( " getPopupMenuForTable 1");
			if( e.getButton() == MouseEvent.BUTTON3 ) {	//显示弹出菜单
				
				//System.out.println (getTable().getX()+e.getX());
				//getPopupMenuForTable().locate( getTable().getX()+e.getX(), getTable().getY()+e.getY() );
				//getPopupMenuForTable().setVisible( true );
				getPopupMenuForTable().setSelected(null);
				getPopupMenuForTable().show( e.getComponent(), e.getX(), e.getY() );
				
			}
		}
		
	}
 
	/**
	 * This method initializes table	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private PlainTable getMainTable(){
		if (mainTable==null) {
			mainTable = new PlainTable();	 
		    Object[][] data = null;
		    
		    // A DefaultTableModel object is created and initialized with some
		    // data and headers.

		    //DefaultTableModel dtm = new DefaultTableModel(2, 3);
		    //DefaultTableModel dtm = new UneditableTableModel(2, 3);
		    DefaultTableModel dtm = new DefaultTableModel(2, 3); //no new methods
		    dtm.setDataVector(data, MainTable_Headers );
		    PlainTableModel sorter = new PlainTableModel( dtm, mainTable.getTableHeader());
		    sorter.setColumnEditable( MainTable_Column_Index_Name );
//		    RowSorter sorter = new TableRowSorter(dtm);
		    sorter.setColumnClass(MainTable_Column_Index_Size, java.lang.Integer.class);
		    mainTable.setModel(sorter);
		    
//		    table.setRowSorter(sorter);
		    
		    mainTable.setGridColor(Color.LIGHT_GRAY);
		    mainTable.setRowSelectionAllowed(true);
		    if (mainTable.getRowCount()>0) {
			    mainTable.setRowSelectionInterval(0, 0);	
			}
		    mainTable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		    mainTable.setShowGrid(true);
//		    mainTable.setRowHeight(21);
//		    mainTable.getTableHeader().setReorderingAllowed(false);
		    mainTable.addMouseListener( this );
		    mainTable.addKeyListener( this );
		    
		    this.update(mainTable);
		    
	        mainTable.getModel().addTableModelListener(new TableModelListener(){
    			String synStr = "demo";
				public void tableChanged(TableModelEvent e) {
					synchronized( synStr ){
					if (e.getType() == TableModelEvent.UPDATE) {
							/*
							 * do some thing 获得编辑后单元格得值
							 */
							if (e.getLastRow()>mainTable.getRowCount()) {
								return ;
							}
							log.info("e.getLastRow()="+e.getLastRow());
							if (e.getLastRow()<0) {
								return;
							}
							final String newValue = mainTable.getValueAt(e.getLastRow(),
									MainTable_Column_Index_Name ).toString();
							if (newValue==null || newValue.equals(tableOldValue)) { //没变化则不处理
								return ;
							}
							tableOldValue = newValue;
							String fileName = getMainTable().getModel().getValueAt(e.getLastRow(), MainTable_Column_Index_Name).toString();
							String fileUri = getMainTable().getModel().getValueAt(e.getLastRow(), MainTable_Column_Index_Uri).toString();
							String filePath = new File(fileUri).getParent(); 
							
							String newUri = filePath +File.separator+ newValue;
							File file = new File(fileUri);
							file.renameTo( new File(newUri) );
							getMainTable().getModel().setValueAt( newUri,e.getLastRow(), MainTable_Column_Index_Uri);
							//同步收藏FMT_FavoriteFiles、复制FMT_FileCopy、备份FMT_FileBackup的目录
							ResourceMasterDao rmd = new ResourceMasterDaoImpl();
							try {
								rmd.synchResourceUri(fileUri, newUri);
							} catch (Exception e1) {
								e1.printStackTrace();
							}
						}
					    
						currentStatusInfor = statusBar_renameSuccessfully;
						setStatus( StatusBar_Index_One, currentStatusInfor);
					}
				}
			});
		}
		return mainTable;
		
	}

	private void update(JTable mainTable) {
	    // 更改列宽度
//	    setAllColWith(table);
	    TableColumn tc = null;
	    TableColumnModel tcm = mainTable.getColumnModel(); 
        for(int i=0; i <MainTable_Columns_Width.length; i++)   {
            tc   =   tcm.getColumn(i);
            tc.setPreferredWidth(MainTable_Columns_Width[i]); 
            
        }
        
        this.getMainTable().showZebraCross();

        // column size to right
        tc = tcm.getColumn( MainTable_Column_Index_Size );//column name
        DefaultTableCellRenderer renderer = new ZebraCrossTableCellRenderer();
        renderer.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        tc.setCellRenderer(renderer);
        
        TableCellRenderer myRenderer = new IconTableCellRenderer(mainTable, MainTable_Column_Index_Uri, true);
        tc = tcm.getColumn( MainTable_Column_Index_Name );//column name
        tc.setCellRenderer(myRenderer);
        //mainTable.getColumnModel().removeColumn(mainTable.getColumn(MainTable_Column_Index_Uri));
        int[] cols = {MainTable_Column_Index_Uri};
        DirectorComponentUtils.hideTableColumns(mainTable, cols); 

	}

	private JScrollPane bottomScrollPanel;
	private JPopupMenu popupMenuForTable;
	private JMenuItem jpmi_MainTable_Open;
	private JMenuItem jpmi_MainTable_OpenPath;
	private JMenuItem jpmi_MainTable_Add2FavoriteFile;
	private JMenuItem jpmi_MainTable_Add2FileCopy;
	private JMenuItem jpmi_MainTable_Rename;
	private JMenuItem jpmi_MainTable_Delete;
	private JMenuItem jpmi_MainTable_Search;
	private JMenuItem jpmi_MainTable_SearchDisk;
	/**
	 * Table的弹出式菜单
	 */
	private JPopupMenu getPopupMenuForTable(){
		
		if(popupMenuForTable == null){
			popupMenuForTable = new JPopupMenu();
			
			jpmi_MainTable_Open = new JMenuItem();
			jpmi_MainTable_Open.setText("open");
			jpmi_MainTable_Open.addActionListener( this );
			jpmi_MainTable_Open.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK) );
			jpmi_MainTable_OpenPath = new JMenuItem();
			jpmi_MainTable_OpenPath.setText("open path");
			jpmi_MainTable_OpenPath.addActionListener( this );
			jpmi_MainTable_OpenPath.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_P,Event.CTRL_MASK) );
			
			jpmi_MainTable_Add2FavoriteFile = new JMenuItem();
			jpmi_MainTable_Add2FavoriteFile.setText("add to favorite files");
			jpmi_MainTable_Add2FavoriteFile.addActionListener( this );
			jpmi_MainTable_Add2FavoriteFile.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_A,Event.CTRL_MASK) );
			
			jpmi_MainTable_Add2FileCopy = new JMenuItem();
			jpmi_MainTable_Add2FileCopy.setText("add to current file copy list");
			jpmi_MainTable_Add2FileCopy.addActionListener( this );
			jpmi_MainTable_Add2FileCopy.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK) );
			
			jpmi_MainTable_Rename = new JMenuItem();
			jpmi_MainTable_Rename.setText("rename");
			jpmi_MainTable_Rename.addActionListener( this );
			jpmi_MainTable_Rename.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_R,Event.CTRL_MASK) );
			
			jpmi_MainTable_Delete = new JMenuItem();
			jpmi_MainTable_Delete.setText("delete");
			jpmi_MainTable_Delete.addActionListener( this );
			jpmi_MainTable_Delete.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_D,Event.CTRL_MASK) );
			
			jpmi_MainTable_Search = new JMenuItem();
			jpmi_MainTable_Search.setText("Find in current list");
			jpmi_MainTable_Search.addActionListener( this );
			jpmi_MainTable_Search.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F,Event.CTRL_MASK) );
			
			jpmi_MainTable_SearchDisk = new JMenuItem();
			jpmi_MainTable_SearchDisk.setText("Search full disk");
			jpmi_MainTable_SearchDisk.addActionListener( this );
			jpmi_MainTable_SearchDisk.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S,Event.CTRL_MASK) );
			
			popupMenuForTable.add( jpmi_MainTable_Open );
			popupMenuForTable.add( jpmi_MainTable_OpenPath );
			popupMenuForTable.addSeparator();
			popupMenuForTable.add( jpmi_MainTable_Add2FavoriteFile );
			popupMenuForTable.add( getAddFileOpenTaskAwokeMenuItem() ); //添加为提醒紧跟添加到收藏，保持系统一致性
			popupMenuForTable.add( jpmi_MainTable_Add2FileCopy );
			popupMenuForTable.addSeparator();
			popupMenuForTable.add( jpmi_MainTable_SearchDisk );
			popupMenuForTable.add( jpmi_MainTable_Search );
			popupMenuForTable.add( jpmi_MainTable_Rename );
			popupMenuForTable.add( jpmi_MainTable_Delete );
			
		}
		
		return popupMenuForTable; 
		
	}


	public void keyPressed(KeyEvent e) {
		Object obj= e.getSource();

		if (obj==mainTable) {
			if(mainTable.getSelectedRow()<=mainTable.getRowCount()
					&& mainTable.getSelectedRow()>-1 ){
				tableOldValue = mainTable.getValueAt(mainTable.getSelectedRow(), MainTable_Column_Index_Name)+"";
			} 
		}
		
		// 回车键，展开文件夹
		if (e.getKeyCode() == KeyEvent.VK_ENTER ) {
			if (obj==locationTextField) {
				String fStr = locationTextField.getText();
				if (fStr==null || fStr.trim().equals("")) {
					return ;
				}
				setCurrentFolder(fStr, locationTextField);
			} else {
	    		//System.out.println("2222222222222");
		    	int selRow = getMainTable().getSelectedRow(); //获得开始回车所在的行。
	    		log.info("selRow="+selRow);
		    	if (selRow>-1) {
		    		// keyPressed换行前调用， keyTyped换行后调用
			    	//getTable().setRowSelectionInterval(selRow, selRow);
			    	executeOpenCurrentFile();
			    	e.consume();
				}
		    }
			
		}else if (e.getKeyCode() == KeyEvent.VK_F && e.isControlDown()
	    		&& (obj==mainTable||obj==this
	    				||obj==locationTextField
	    				||obj==leftFileTree) ) {
			
			this.getRightSplitPane().setDividerLocation(CommonSearchable.CommonSearchPanel_Hight);
			this.getCommonSearchPanel().getKeywordTextField().requestFocusInWindow();
			e.consume();
	    	
		}else if (e.getKeyCode() == KeyEvent.VK_S && e.isControlDown()
	    		&& (obj==mainTable||obj==this
	    				||obj==locationTextField
	    				||obj==leftFileTree) ) {

			this.mainFrame.executeLocalSearch();
//			this.mainFrame.getMainTabbedPane().setSelectedIndex( MainFrame.MainTabPane_LocalSearchMainPanel_Index );	
//			this.mainFrame.getLocalSearchMainPanel().getKeywordTextField().requestFocusInWindow();
	    	e.consume();
	    	
		} else if(e.getKeyCode() == KeyEvent.VK_I ){
			
	    }
		
	}


	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}


	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void closeCommonSearchPanel() {
		this.getRightSplitPane().setDividerLocation(0);
		this.getMainTable().requestFocusInWindow();
	}


	private String msgDialog_infoSureDelete = null;
	private String statusBar_renameSuccessfully;
	private String statusBar_currentFileListInfo;
	@Override
	public void update(Observable o, Object arg) {
		super.update(o, arg);
		
		//System.out.println(Locale.getDefault());
		ResourceBundle bundle = I18nUtils.getBundle(DirectorConstants.I18n_Language_Name);
		
		lbl_location.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "lbl_location.Text"));
		msgDialog_infoSureDelete = I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "msgDialog_infoSureDelete.Message");
		msgDialog_infoSuccessRowNum = I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "msgDialog_infoSuccessRowNum.Message");
		msgDialog_infoSuccessFailRowNum = I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "msgDialog_infoSuccessFailRowNum.Message");
		statusBar_renameSuccessfully = I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "status_renameSuccessfully.Text");
		statusBar_currentFileListInfo = I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "status_currentFileListInfo.Text");
		
		//table
	    Vector<String> columnIdentifiers = new Vector<String>();
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "table.col00.Text"));
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "table.col01.Text"));
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "table.col02.Text"));
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "table.col03.Text"));
	    columnIdentifiers.add("uri");//不可见I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "table.col04.Text")
	    DefaultTableModel dtm = (this.getMainTable().getModel()).getTableModel();
	    dtm.setColumnIdentifiers(columnIdentifiers);
	    
	    //refresh table columns
	    this.update( this.mainTable );
        
        // popup menu for table 
        getPopupMenuForTable();
        jpmi_MainTable_Open.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_Open.Text"));
        jpmi_MainTable_OpenPath.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_OpenPath.Text"));
        jpmi_MainTable_Add2FavoriteFile.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_Add2FavoriteFile.Text"));
        jpmi_MainTable_Add2FileCopy.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_Add2FileCopy.Text"));
        jpmi_MainTable_Rename.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_Rename.Text"));
        jpmi_MainTable_Delete.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_Delete.Text"));
        jpmi_MainTable_Search.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_Search.Text"));
        jpmi_MainTable_SearchDisk.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_SearchDisk.Text"));
        //jpmi_MainTable_Search.setText(I18nUtil.getBundleString(bundle, FileExplorerMainPanel.class, "jpmi_MainTable_Search.Text"));
        jpmi_MainTable_Search.setText(I18nUtil.getBundleString(bundle, DirectorPanel.class, "jpmi_MainTable_Search.Text"));
        
	    if (this.mainTable!=null) {
		    this.currentStatusInfor = StringUtils.replace(this.statusBar_currentFileListInfo, "${count}", mainTable.getRowCount()+"");
		}
	}
	
	//------------------------------ MainTable End -------------------
	
	
}  //  @jve:decl-index=0:visual-constraint="10,10"
